package com.atlin.license;

import com.atlin.model.LicenseCheckModel;
import com.atlin.model.LicenseVerifyParam;
import de.schlichtherle.license.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.prefs.Preferences;

/**
 * License校验类
 */
@Slf4j
public class LicenseVerify {

    /**
     * 安装License证书
     */
    public synchronized LicenseContent install(LicenseVerifyParam param) {
        LicenseContent result = null;
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //1. 安装证书
        try {
            LicenseManager licenseManager = LicenseManagerHolder.getInstance(initLicenseParam(param));
            licenseManager.uninstall();
            result = licenseManager.install(new File(param.getLicensePath()));
            log.info("证书安装成功，证书有效期：{} - {}", format.format(result.getNotBefore()), format.format(result.getNotAfter()));
        } catch (Exception e) {
            log.error("证书安装失败！", e);
        }

        return result;
    }

    /**
     * 校验License证书
     */
    public LicenseContent verify() {
        LicenseManager licenseManager = LicenseManagerHolder.getInstance(null);
        LicenseContent licenseContent = null;
        try {
            licenseContent = licenseManager.verify();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return licenseContent;
    }

    /**
     * 校验License证书
     */
    public boolean verify(HttpServletRequest request) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            LicenseContent licenseContent = this.verify();
            this.verifyPermission(licenseContent, request);
            log.info("证书校验通过，证书有效期：{} - {}", format.format(licenseContent.getNotBefore()), format.format(licenseContent.getNotAfter()));
            return true;
        } catch (Exception e) {
            log.error("证书校验失败！", e);
            return false;
        }
    }

    /**
     * 校验权限
     */
    public boolean verifyPermission(LicenseContent licenseContent, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        LicenseCheckModel licenseCheckModel = (LicenseCheckModel) licenseContent.getExtra();
        log.info("许可路由列表：{}", licenseCheckModel.getRoutePath());
        log.info("访问路由：{}", requestURI);
        return true;
    }
    

    /**
     * 初始化证书参数
     */
    private LicenseParam initLicenseParam(LicenseVerifyParam param) {
        Preferences preferences = Preferences.userNodeForPackage(LicenseVerify.class);

        CipherParam cipherParam = new DefaultCipherParam(param.getStorePass());

        KeyStoreParam publicStoreParam = new CustomKeyStoreParam(LicenseVerify.class
                , param.getPublicKeysStorePath()
                , param.getPublicAlias()
                , param.getStorePass()
                , null);

        return new DefaultLicenseParam(param.getSubject()
                , preferences
                , publicStoreParam
                , cipherParam);
    }

}
